package com.springboot.idempotence.redis;

import com.springboot.idempotence.redis.exception.TokenException;
import com.springboot.idempotence.redis.utils.Constant;
import com.springboot.idempotence.redis.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private RedisService redisService;

    @Override
    public String createToken() {
        String uuid = StringUtils.uuid();
        StringBuffer token = new StringBuffer();
        try {
            token.append(Constant.Redis.TOKEN_PREFIX).append(":").append(uuid);
            String tokenStr = token.toString();
            redisService.setEx(tokenStr, tokenStr, 1000L);
            return tokenStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) throws TokenException {
        String token = request.getHeader(Constant.TOKEN_NAME);
        if (StringUtils.isEmpty(token)) {//header中不存在token
            token = request.getParameter(Constant.TOKEN_NAME);
            if (StringUtils.isEmpty(token)) {// parameter中也不存在token
                throw new TokenException(TokenException.ResponseCode.ILLEGAL_ARGUMENT, 200);
            }
        }
        if (!redisService.exists(token)) {
            throw new TokenException(TokenException.ResponseCode.REPETITIVE_OPERATION, 200);
        }
        boolean flag = redisService.remove(token);
        if (!flag) {
            throw new TokenException(TokenException.ResponseCode.REPETITIVE_OPERATION, 200);
        }
        return true;
    }
}
